package com.yunli.mall.common.util;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author wangyue
 * @description
 * @date 2020/6/30 6:47 PM
 */
public class AppContext {

    private static final ThreadLocal<ConcurrentMap<String, Object>> THREAD_LOCAL = ThreadLocal.withInitial(ConcurrentHashMap::new);
    private static final String TOKEN = "token";
    private static final String USER_ID = "userId";

    private AppContext() {
    }

    /**
     *
     */
    public static synchronized void removeAll() {
        THREAD_LOCAL.remove();
    }

    /**
     * @param userId
     * @return
     */
    public static synchronized boolean setUserId(String userId) {
        if (null == userId) {
            return false;
        }
        THREAD_LOCAL.get().putIfAbsent(USER_ID, userId);
        return true;
    }

    /**
     * @return
     */
    public static synchronized String getUserId() {
        return THREAD_LOCAL.get().containsKey(USER_ID) ? String.valueOf(THREAD_LOCAL.get().get(USER_ID)) : null;
    }

    /**
     * @param token
     * @return
     */
    public static synchronized boolean setToken(String token) {
        if (null == token) {
            return false;
        }
        THREAD_LOCAL.get().putIfAbsent(TOKEN, token);
        return true;
    }

    /**
     * @return
     */
    public static synchronized String getToken() {
        return THREAD_LOCAL.get().containsKey(TOKEN) ? String.valueOf(THREAD_LOCAL.get().get(TOKEN)) : null;
    }

    /**
     * @param key
     * @param value
     */
    public static synchronized boolean setObject(String key, Object value) {
        if (null == value) {
            return false;
        }
        THREAD_LOCAL.get().put(key, value);
        return true;
    }

    /**
     * @param key
     * @return
     */
    public static synchronized Object getObject(String key) {
        return THREAD_LOCAL.get().getOrDefault(key, null);
    }

}
